#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
游戏管理器
负责整个游戏的状态管理和核心逻辑
"""

import time
from typing import Optional, Dict, Any
from character.character_manager import CharacterManager
from idle.idle_manager import IdleManager
from battle.battle_manager import BattleManager

class GameManager:
    """
    游戏管理器
    """
    
    def __init__(self):
        """
        初始化游戏管理器
        """
        self.character_manager = CharacterManager()
        self.idle_manager = IdleManager()
        self.battle_manager = BattleManager()
        
        self.game_state = "menu"  # menu, character_select, idle, battle
        self.running = True
        self.start_time = time.time()
        
        print("游戏管理器初始化完成")
    
    def get_current_character(self):
        """
        获取当前角色
        """
        return self.character_manager.current_character
    
    def create_character(self, name: str, character_class: str = "战士"):
        """
        创建角色
        """
        return self.character_manager.create_character(name, character_class)
    
    def select_character(self, character_id: str):
        """
        选择角色
        """
        return self.character_manager.select_character(character_id)
    
    def get_all_characters(self):
        """
        获取所有角色
        """
        return self.character_manager.get_all_characters()
    
    def start_idle(self, location: str):
        """
        开始挂机
        """
        current_character = self.get_current_character()
        if not current_character:
            return False, "请先选择角色"
        
        success, message = self.idle_manager.start_idle(current_character, location)
        if success:
            self.game_state = "idle"
        
        return success, message
    
    def stop_idle(self):
        """
        停止挂机
        """
        current_character = self.get_current_character()
        if not current_character:
            return False, "请先选择角色"
        
        success, message, rewards = self.idle_manager.stop_idle(current_character)
        if success:
            self.game_state = "menu"
            # 应用挂机奖励
            if rewards.get('exp', 0) > 0:
                current_character.gain_exp(rewards['exp'])
                self.character_manager.save_characters()
        
        return success, message, rewards
    
    def get_idle_status(self):
        """
        获取挂机状态
        """
        current_character = self.get_current_character()
        if not current_character:
            return None
        
        return self.idle_manager.get_idle_status(current_character)
    
    def update_idle_rewards(self):
        """
        更新挂机奖励（实时计算）
        """
        current_character = self.get_current_character()
        if not current_character or not current_character.is_idle:
            return None
        
        return current_character.get_idle_rewards()
    
    def get_available_idle_locations(self):
        """
        获取可用的挂机地点
        """
        return self.idle_manager.get_available_locations()
    
    def create_battle(self, battle_type: str, team: int):
        """
        创建战斗
        """
        current_character = self.get_current_character()
        if not current_character:
            raise Exception("请先选择角色")
        
        battle = self.battle_manager.create_battle(battle_type)
        team_name = "a" if team == 1 else "b"
        success, message = self.battle_manager.join_battle(current_character, battle.id, team_name)
        
        if not success:
            raise Exception(message)
        
        return battle.id
    
    def get_battle(self, battle_id: str):
        """
        获取战斗信息
        """
        battle = self.battle_manager.get_battle(battle_id)
        if not battle:
            return None
        
        # 转换为GUI期望的格式
        battle_info = battle.get_battle_info()
        return {
            'id': battle_info['id'],
            'type': battle_info['battle_type'],
            'status': battle_info['status'],
            'team1': [{'id': char.id, 'name': char.name} for char in battle.team_a],
            'team2': [{'id': char.id, 'name': char.name} for char in battle.team_b],
            'winner_team': 1 if battle_info['winner'] == 'team_a' else (2 if battle_info['winner'] == 'team_b' else None),
            'end_time': battle_info['finished_at']
        }
    
    def join_battle(self, battle_id: str, team: int):
        """
        加入战斗
        """
        current_character = self.get_current_character()
        if not current_character:
            raise Exception("请先选择角色")
        
        team_name = "a" if team == 1 else "b"
        success, message = self.battle_manager.join_battle(current_character, battle_id, team_name)
        
        if not success:
            raise Exception(message)
        
        return True
    
    def leave_battle(self):
        """
        离开战斗
        """
        current_character = self.get_current_character()
        if not current_character:
            raise Exception("请先选择角色")
        
        success, message = self.battle_manager.leave_battle(current_character)
        
        if not success:
            raise Exception(message)
        
        return True
    
    def start_battle(self, battle_id: str):
        """
        开始战斗
        """
        success, message = self.battle_manager.start_battle(battle_id)
        
        if not success:
            raise Exception(message)
        
        # 获取战斗结果
        battle = self.battle_manager.get_battle(battle_id)
        if battle:
            battle_info = battle.get_battle_info()
            return {
                'winner_team': 1 if battle_info['winner'] == 'team_a' else (2 if battle_info['winner'] == 'team_b' else None),
                'battle_log': battle_info['battle_log']
            }
        
        return None
    
    def get_available_battles(self):
        """
        获取可用战斗列表
        """
        battles = self.battle_manager.get_available_battles()
        result = []
        
        for battle_info in battles:
            battle = self.battle_manager.get_battle(battle_info['id'])
            if battle:
                result.append({
                    'id': battle_info['id'],
                    'type': battle_info['battle_type'],
                    'status': battle_info['status'],
                    'team1': [{'id': char.id, 'name': char.name} for char in battle.team_a],
                    'team2': [{'id': char.id, 'name': char.name} for char in battle.team_b]
                })
        
        return result
    
    def get_battle_history(self):
        """
        获取战斗历史
        """
        history = self.battle_manager.get_battle_history()
        result = []
        
        for battle_info in history:
            battle = self.battle_manager.get_battle(battle_info['id'])
            if battle:
                result.append({
                    'id': battle_info['id'],
                    'type': battle_info['battle_type'],
                    'status': battle_info['status'],
                    'team1': [{'id': char.id, 'name': char.name} for char in battle.team_a],
                    'team2': [{'id': char.id, 'name': char.name} for char in battle.team_b],
                    'winner_team': 1 if battle_info['winner'] == 'team_a' else (2 if battle_info['winner'] == 'team_b' else None),
                    'end_time': battle_info['finished_at']
                })
        
        return result
    
    def save_game(self):
        """
        保存游戏数据
        """
        self.character_manager.save_characters()
        print("游戏数据已保存")
    
    def get_game_stats(self) -> Dict[str, Any]:
        """
        获取游戏统计信息
        """
        play_time = time.time() - self.start_time
        character_stats = self.character_manager.get_character_stats()
        
        return {
            'play_time': play_time,
            'game_state': self.game_state,
            'character_stats': character_stats,
            'current_character': self.get_current_character().name if self.get_current_character() else None
        }
    
    def shutdown(self):
        """
        关闭游戏
        """
        self.save_game()
        self.running = False
        print("游戏已关闭")